//
//  ViewController.m
//  weiguang
//
//  Created by Zheng on 2018/5/14.
//  Copyright © 2018年 Zheng. All rights reserved.
//
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import "mainMap.h"
#import "RouteAnnotation.h"
#import <CoreLocation/CoreLocation.h>
#import <BaiduMapAPI_Map/BMKMapView.h>
#import <BaiduMapAPI_Location/BMKLocationService.h>
#import <BaiduMapAPI_Map/BMKPointAnnotation.h>
#import <BaiduMapAPI_Map/BMKPinAnnotationView.h>
#import <BaiduMapAPI_Search/BMKRouteSearch.h>
#import <BaiduMapAPI_Search/BMKGeocodeSearch.h>
@interface mainMap ()<BMKRouteSearchDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeneralDelegate>
{
    BMKMapPoint userLocation;
    BMKMapPoint destination;
}
@property(nonatomic,strong)BMKRouteSearch* routesearch;;
@end

@implementation mainMap

-(void)getDestinationLocation{//从后台获取残疾人位置
    self->destination =BMKMapPointMake(30.615305,114.362304 );
}
/**
 *用户位置更新后，会调用此函数
 *@param location 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)location
{
    self->userLocation = BMKMapPointMake(location.location.coordinate.latitude, location.location.coordinate.longitude);
    CLLocation *loc1 = [[CLLocation alloc] initWithLatitude: userLocation.x longitude: userLocation.y];
    CLLocation *loc2 = [[CLLocation alloc]initWithLatitude:destination.x longitude:destination.y];
    CLLocationDistance distance = [loc2 distanceFromLocation:loc1];
    NSLog(@"%f",distance);
    [mapView updateLocationData:location];
}
/**
  *根据anntation生成对应的View
  *@param mapView 地图View
  *@param annotation 指定的标注
  *@return 生成的标注View
  */
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation{
//   if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
//        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
//        newAnnotationView.animatesDrop = YES;
//        newAnnotationView.annotation = annotation;
//        //这里我根据自己需要，继承了BMKPointAnnotation，添加了标注的类型等需要的信息
//        MyBMKPointAnnotation *tt = (MyBMKPointAnnotation *)annotation;
//
//        //判断类别，需要添加不同类别，来赋予不同的标注图片
//        if (tt.profNumber == 100000) {
//            newAnnotationView.image = [UIImage imageNamed:@"ic_map_mode_category_merchants_normal.png"];
//        }else if (tt.profNumber == 100001){
//
//        }
//        //设定popView的高度，根据是否含有缩略图
//        double popViewH = 60;
//        if (annotation.subtitle == nil) {
//            popViewH = 38;
//        }
    static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
    BMKPinAnnotationView*annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
    }
    if([annotation.title isEqualToString:@"handicap"]){
        UIView *popView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 90)];
        
        popView.backgroundColor = [UIColor grayColor];
        [popView.layer setMasksToBounds:YES];
        [popView.layer setCornerRadius:10.0];
        popView.alpha = 0.7;
        //设置弹出气泡图片
        UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"handicap"]];
        image.backgroundColor=[UIColor whiteColor];
        image.frame = CGRectMake(5, 5, 70, 70);
        image.layer.cornerRadius = image.bounds.size.width / 2;
        image.layer.masksToBounds=YES;
        [popView addSubview:image];
        
        //自定义气泡的内容，添加子控件在popView上
        UILabel *driverName = [[UILabel alloc]initWithFrame:CGRectMake(70, 10, 110, 40)];
        driverName.text = @"name";
        driverName.numberOfLines = 0;
        driverName.backgroundColor = [UIColor clearColor];
        driverName.font = [UIFont systemFontOfSize:20];
        driverName.textColor = [UIColor blackColor];
        driverName.textAlignment = NSTextAlignmentCenter;
        [popView addSubview:driverName];
        
        UIButton *searchBn = [[UIButton alloc]initWithFrame:CGRectMake(80, 50, 110, 35) ];
        searchBn.layer.cornerRadius = 10;
        [searchBn setTitle:@"查看路线" forState:UIControlStateNormal];
        searchBn.backgroundColor = [UIColor blueColor];
        searchBn.titleLabel.numberOfLines = 0;
        [searchBn addTarget:self action:@selector(searchLine) forControlEvents:UIControlEventTouchUpInside];
        [popView addSubview:searchBn];
        
        //
        BMKActionPaopaoView *pView = [[BMKActionPaopaoView alloc]initWithCustomView:popView];
        pView.frame = CGRectMake(0, 0, 200, 90);
        if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
            annotationView.image=[UIImage imageNamed:@"handicap1"];
            annotationView.canShowCallout= YES;      //设置气泡可以弹出，默认为NO
            annotationView.animatesDrop=NO;         //设置标注动画显示，默认为NO
            annotationView.draggable = NO;          //设置标注可以拖动，默认为NO
            ((BMKPinAnnotationView*)annotationView).paopaoView = nil;
            ((BMKPinAnnotationView*)annotationView
             ).paopaoView = pView;
        }else{
            return nil;
        }
    }else{
        if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
            annotationView.image = [UIImage imageNamed:@"yuan"];
            annotationView.canShowCallout= YES;      //设置气泡可以弹出，默认为NO
            annotationView.animatesDrop=NO;         //设置标注动画显示，默认为NO
            annotationView.draggable = NO;          //设置标注可以拖动，默认为NO
        }else{
            return nil;
        }
    }
    return annotationView;
//        return newAnnotationView;
//    }
//    return nil;
   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    locService = [[BMKLocationService alloc]init];
    locService.delegate = self;
    //启动LocationService
    [locService startUserLocationService];
    mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-self.navigationController.navigationBar.bounds.size.height)];
    mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    mapView.showsUserLocation = YES;//显示定位图层
    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backtomain)];
    self.navigationController.navigationBar.translucent = NO;
    //TODO:如果是残疾人用户 进一个while循环每隔2-3分钟发位置信息给数据库
    mapView.showMapScaleBar=YES;
    mapView.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态为普通定位模式
    [self.view addSubview:mapView];
 
}
-(void)viewDidAppear:(BOOL)animated{
    BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
    [self getDestinationLocation];
    annotation.coordinate = CLLocationCoordinate2DMake(self->destination.x, self->destination.y);
    annotation.title = @"handicap";
    [mapView addAnnotation:annotation];
}

-(void)viewWillAppear:(BOOL)animated
{
    [mapView viewWillAppear];
     _routesearch = [[BMKRouteSearch alloc]init];
     _routesearch.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    mapView.delegate=self;
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [mapView viewWillDisappear];
    _routesearch.delegate=nil;
    mapView.delegate = nil; // 不用时，置nil
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)searchLine{
    BMKPlanNode* start = [[BMKPlanNode alloc]init];
    //        start.name = _startAddrText.text;
    //        start.cityName = _startCityText.text;
    [start setPt:CLLocationCoordinate2DMake(self->userLocation.x, self->userLocation.y)];
    BMKPlanNode* end = [[BMKPlanNode alloc]init];
    //        end.name = _endAddrText.text;
    //        end.cityName = _endCityText.text;
    [end setPt:CLLocationCoordinate2DMake(destination.x, destination.y)];
    BMKWalkingRoutePlanOption *walkingRouteSearchOption = [[BMKWalkingRoutePlanOption alloc]init];
    walkingRouteSearchOption.from = start;
    walkingRouteSearchOption.to = end;
    BOOL flag = [_routesearch walkingSearch:walkingRouteSearchOption];
    if(flag)
    {
        NSLog(@"walk检索发送成功");
    }
    else
    {
        NSLog(@"walk检索发送失败");
    }
}
- (void)onGetWalkingRouteResult:(BMKRouteSearch*)searcher result:(BMKWalkingRouteResult*)result errorCode:(BMKSearchErrorCode)error
{
    NSLog(@"onGetWalkingRouteResult error:%d", (int)error);
    NSArray *temp=[NSArray arrayWithArray:mapView.annotations];
    NSMutableArray* tempArray = [[NSArray arrayWithArray:mapView.annotations]mutableCopy];
    for(int i=0;i<tempArray.count;i++){
        if([[tempArray[i] title] isEqualToString:@"handicap"]){
            [tempArray removeObjectAtIndex:i];
        }
    }
    
    NSArray *array=[tempArray copy];
    [mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:mapView.overlays];
    [mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        BMKWalkingRouteLine* plan = (BMKWalkingRouteLine*)[result.routes objectAtIndex:0];
        NSInteger size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKWalkingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = @"起点";
                item.type = 0;
                [mapView addAnnotation:item]; // 添加起点标注
                
            }
            if(i==size-1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = @"终点";
                item.type = 1;
                [mapView addAnnotation:item]; // 添加起点标注
            }
            //添加annotation节点
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.entraceInstruction;
            item.degree = transitStep.direction * 30;
            item.type = 4;
            if(item.coordinate.latitude == destination.x && item.coordinate.longitude ==destination.y){
                break;
            }
            [mapView addAnnotation:item];
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKWalkingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        // 通过points构建BMKPolyline
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [mapView addOverlay:polyLine]; // 添加路线overlay
        delete []temppoints;
        [self mapViewFitPolyLine:polyLine];
        [mapView addAnnotations:temp];
    } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR) {
        NSLog(@"出现问题");
    }
}
#pragma mark - 私有

//根据polyline设置地图范围
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    CGFloat leftTopX, leftTopY, rightBottomX, rightBottomY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    // 左上角顶点
    leftTopX = pt.x;
    leftTopY = pt.y;
    // 右下角顶点
    rightBottomX = pt.x;
    rightBottomY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        leftTopX = pt.x < leftTopX ? pt.x : leftTopX;
        leftTopY = pt.y < leftTopY ? pt.y : leftTopY;
        rightBottomX = pt.x > rightBottomX ? pt.x : rightBottomX;
        rightBottomY = pt.y > rightBottomY ? pt.y : rightBottomY;
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(leftTopX, leftTopY);
    rect.size = BMKMapSizeMake(rightBottomX - leftTopX, rightBottomY - leftTopY);
    UIEdgeInsets padding = UIEdgeInsetsMake(30, 0, 100, 0);
    BMKMapRect fitRect = [mapView mapRectThatFits:rect edgePadding:padding];
    [mapView setVisibleMapRect:fitRect];
}
//MARK:返回主页面
- (void)backtomain {
    [self.navigationController popViewControllerAnimated:YES];
}
- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
{
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.fillColor = [UIColor cyanColor];
        polylineView.strokeColor = [UIColor orangeColor];
        polylineView.lineWidth=2;
        return polylineView;
    }
    return nil;
}
@end
